/* eslint-disable @typescript-eslint/no-unused-vars */
import { List, Modal, Radio, Icon, InputItem } from 'antd-mobile-v2';
import * as React from 'react';
import { Props, State } from '../type';
import {
  GetDataByExternalUrl,
  GetDataByExternalUrlR
} from '../../common/services';
import './index.less';
import styles from './index.module.less';
import noDataImg from '@/assets/images/no-data.png';
import { List as VList, ListRowProps } from 'react-virtualized';
import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer';
import AntdRefreshList from '@/components/antd-refresh-list';
import classnames from 'classnames';
let debounceTimer = null;

export class RadioSelect extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();
  prevData: string;
  autoFocusInst: React.RefObject<HTMLInputElement>;
  constructor(props: Props) {
    super(props);
    this.state = {
      isModal: false,
      options: [],
      sourceOptions: [], // 接口返回的未经处理的源数据
      showModal: false,
      selectedValue: null,
      // checkedValue: '',
      checkedLabel: '',
      searchValue: '',
      loading: false,
      noData: false,
      otherParams: {} // 接口请求需要的其他参数（包括加载更多的参数）
    };
    this.prevData = '';
    this.autoFocusInst = React.createRef();
  }

  public UNSAFE_componentWillReceiveProps() {
    const newData = this.props.form?.getFieldValue(this.props.code);
    if (this.prevData !== newData) {
      this.prevData = newData;
      this.setDefaultData();
    }
    if (this.props.resetOption) {
      this.setState({
        customOptionItem: {
          value: '',
          text: ''
        }
      });
    }
  }

  public componentDidUpdate(_prevProps, prevState) {
    if (
      !prevState.showModal &&
      this.state.showModal &&
      this.props.externalOption?.searchWithoutData === false
    ) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
      // @ts-ignore
      this.autoFocusInst.focus();
    }
  }

  public componentDidMount() {
    setTimeout(() => {
      this.getExternalData();
      this.setDefaultData();
    }, 300);
  }

  setDefaultData = () => {
    const value = this.props.form?.getFieldValue(this.props.code);
    if (value) {
      this.setState({
        selectedValue: value
      });
    }
  };

  private async getExternalData(val?: string) {
    // 是否有设置外部url
    if (
      this.props.useExternal &&
      this.props.externalOption &&
      this.props.externalOption.url
    ) {
      if (this.props.isDeclare) {
        if (
          this.props.externalOption?.searchWithoutData === false &&
          (val === undefined || val === '')
        ) {
          // 不允许不带参数请求接口
          this.setState({
            options: [],
            sourceOptions: []
          });
          return;
        }
        const { otherParams } = this.state;
        const params = {
          ...this.props.externalOption?.searchData,
          keyWord: val,
          ...otherParams
        };
        this.setState({ loading: true });
        const data = await GetDataByExternalUrlR(
          this.props.externalOption.url,
          params
        );
        let list;
        let sourceList;
        if (this.props.externalOption.rows) {
          const dataRows = data?.length ? data : data?.rows;
          sourceList = dataRows;
          list = dataRows?.map((item: any) => {
            const text =
              this.props.externalOption?.formatVal?.text
                ?.split(',')
                ?.map((key: string) => item[key])
                .join('/') || '';
            const descValue =
              item[this.props.externalOption?.formatVal?.descValue] ||
              (this.props.externalOption?.formatVal?.valueType === 'string'
                ? ''
                : 0);
            const disable = this.props.externalOption?.formatVal?.disabled
              ? item[this.props.externalOption?.formatVal?.disabled]
              : false;
            return {
              ...item,
              text: text,
              value: item[this.props.externalOption?.formatVal?.value] || '',
              descTitle: this.props.externalOption?.formatVal?.descTitle || '',
              descValue,
              // 未指定disabled字段时均可选，指定了但是指定字段值不为number类型时不可选，指定字段值小于等于0时不可选
              disabled: !this.props.externalOption?.formatVal?.disabled
                ? false
                : typeof disable === 'number'
                  ? disable <= 0
                  : true
            };
          });
        } else {
          sourceList = data;
          list = data?.map((item: any) => {
            const text =
              this.props.externalOption?.formatVal?.text
                ?.split(',')
                ?.map((key: string) => item[key])
                .join('/') || '';
            return {
              text: text,
              value: item[this.props.externalOption?.formatVal?.value] || ''
            };
          });
        }
        if (list) {
          if (this.props.externalOption.enableLoadMore) {
            // 分页加载的情况
            const { options, sourceOptions } = this.state;
            this.setState({
              options: options.concat(list),
              sourceOptions: sourceOptions.concat(sourceList)
            });
          } else {
            this.setState({
              options: list,
              sourceOptions: sourceList
            });
          }
          if (list.length === 0) {
            this.setState({
              noData: true
            });
          }
        }
        this.setState({ loading: false });
      } else {
        this.setState({ loading: true });
        console.log('this.props.externalOption：',this.props.externalOption);
        const data = await GetDataByExternalUrl(this.props.externalOption, {});
        if (data) {
          this.setState({
            options: data,
            sourceOptions: data,
            loading: false
          });
          if (data.length === 0) {
            this.setState({
              noData: true
            });
          }
        }
      }
    }
  }

  // private onChange = (value: any) => {
  //   if (this.props.form) {
  //     const result = value
  //       ? { value: value.value, text: value.label }
  //       : undefined;
  //     this.props.form.setFieldsValue({ [this.props.code]: result });
  //   }
  //   this.props.onChange && this.props.onChange(value);
  // };

  private showModal = (e: any) => {
    e.preventDefault();
    this.props.clickEffect && this.props.clickEffect();
    if (this.props.disabled) return;
    this.setState({
      showModal: true
    });

    this.getExternalData();
  };

  onClose = () => {
    this.setState({
      showModal: false,
      noData: false
    });
    this.searchChange('');
  };

  public closest(el: any, selector: any) {
    const matchesSelector =
      el.matches ||
      el.webkitMatchesSelector ||
      el.mozMatchesSelector ||
      el.msMatchesSelector;
    while (el) {
      if (matchesSelector.call(el, selector)) {
        return el;
      }
      el = el.parentElement;
    }
    return null;
  }

  onWrapTouchStart = (e: any) => {
    // fix touch to scroll background page on iOS
    if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
      return;
    }
    const pNode = this.closest(e.target, '.am-modal-content');
    if (!pNode) {
      e.preventDefault();
    }
  };

  handleChecked = (item: any, fieldProps: any) => {
    this.setState({
      showModal: false,
      selectedValue: item
      // checkedValue: item.value,
      // checkedLabel: item.label,
    });
    if (this.props.code === 'projectId') {
      const {
        value,
        text,
        authorizeAmount,
        authorizeAmountUsable,
        principalCode,
        projectBalance,
        projectAttribute
      } = item;
      this.props.form?.setFieldsValue({
        projectId: {
          text,
          value,
          principalCode,
          authorizeAmount,
          authorizeAmountUsable,
          projectAttribute,
          projectBalance
        }
      });
    } else {
      this.props.form?.setFieldsValue({
        [this.props.code]: { value: item.value, text: item.text }
      });
    }
    // 先触发一次getFieldProps的onChange方法，标记当前表单已经被手动操作过，用于识别表单编辑后路由离开拦截
    if (fieldProps?.onChange) {
      if (this.props.code === 'projectId') {
        const {
          value,
          text,
          authorizeAmount,
          authorizeAmountUsable,
          principalCode,
          projectAttribute,
          projectBalance
        } = item;
        fieldProps?.onChange({
          text,
          value,
          principalCode,
          authorizeAmount,
          authorizeAmountUsable,
          projectAttribute,
          projectBalance
        });
      } else {
        fieldProps?.onChange({ value: item.value, text: item.text });
      }
    }
    const itemData =
      this.state.sourceOptions.filter(
        (optionsItem: any) =>
          optionsItem.id === item.value || optionsItem.cardCode === item.value
      )[0] || {};
    if (this.props.code === 'projectId') {
      const {
        value,
        text,
        authorizeAmount,
        authorizeAmountUsable,
        principalCode,
        projectAttribute,
        projectBalance
      } = item;
      this.props.onChange &&
        this.props.onChange({
          ...itemData,
          text,
          value,
          principalCode,
          authorizeAmount,
          authorizeAmountUsable,
          projectAttribute,
          projectBalance
        });
    } else {
      this.props.onChange &&
        this.props.onChange({
          ...itemData,
          value: item.value,
          text: item.text
        });
    }
    this.searchChange('');
  };

  searchChange = (val: any) => {
    this.setState({
      searchValue: val,
      otherParams: {
        lastId: ''
      },
      options: [],
      sourceOptions: []
    });
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
      this.getExternalData(val);
    }, 800);
  };
  onCustomChange = (value: any) => {
    this.setState({
      customValue: value
    });
  };

  onSetCustomValue = () => {
    const { customValue, isSetCustomItem } = this.state;

    this.setState(
      {
        customValue: '',
        customOptionItem: {
          value: customValue,
          text: customValue
        }
      },
      () => {
        if (isSetCustomItem) {
          this.setState({
            isSetCustomItem: true
          });
        }
      }
    );
  };
  handleRefresh = () => {};

  handleLoadMore = () => {
    if (this.props.externalOption?.enableLoadMore) {
      const { sourceOptions } = this.state;
      this.setState(
        {
          otherParams: {
            lastId: sourceOptions[sourceOptions.length - 1]?.id || ''
          }
        },
        () => {
          this.getExternalData(this.state.searchValue);
        }
      );
    }
  };

  modal = (radioOptions: any, fieldProps: any) => {
    const { enableSearch, customOption } = this.props;
    const { searchValue, customValue } = this.state;
    const enableStyle = {
      color: '#222222'
    };
    const disabledStyle = {
      color: '#999999'
    };

    return (
      <Modal
        className="radioModal"
        visible={this.state.showModal || false}
        popup
        onClose={this.onClose}
        animationType="slide-up"
        wrapProps={{ onTouchStart: this.onWrapTouchStart }}
      >
        <List
          renderHeader={() => (
            <div className="modalTitle">
              {this.props.name}
              <Icon type="cross" className="closeIcon" onClick={this.onClose} />
            </div>
          )}
        >
          <List.Item>
            {/* <div className="subTitle">分类标题</div> */}
            {!this.props?.hideSearchInput &&
              this.props.enableSearch &&
              this.props.externalOption?.url ? (
                <div className="radioSubTitle">
                  <InputItem
                  // {...this.props.form?.getFieldProps('keyword')}
                    value={this.state.searchValue}
                    clear
                    placeholder={this.props.externalOption?.placeholder}
                    maxLength={30}
                    onChange={this.searchChange}
                    ref={(el) => (this.autoFocusInst = el)}
                    onBlur={() => {
                      this.setState({
                        noData: false
                      });
                    }}
                  >
                  </InputItem>
                </div>
              ) : null}

            {/* 自定义选项功能 */}
            {this.props.customOption && (
              <div className="ensureButtonWrap">
                <div className="radioSubTitle">
                  <InputItem
                    // {...this.props.form?.getFieldProps('keyword')}
                    value={customValue}
                    clear
                    placeholder={`请输入自定义${this.props.name}选项`}
                    maxLength={30}
                    onChange={this.onCustomChange}
                  >
                  </InputItem>
                </div>
                <span
                  key="ensure"
                  className="ensureButton"
                  onClick={this.onSetCustomValue}
                >
                  添加
                </span>
              </div>
            )}

            {radioOptions && radioOptions.length > 0 ? (
              // <AutoSizer disableHeight>
              //   {({ width }) => (
              //     <VList
              //       // ref="List"
              //       // style={{ flex: 1, overflow: 'scroll' }}
              //       width={width}
              //       height={window.screen.height - 102}
              //       rowHeight={56}
              //       // overscanRowCount={50}
              //       rowCount={radioOptions?.length}
              //       rowRenderer={(vProps) => this.rowRenderer(vProps, radioOptions, fieldProps)}
              //     />
              //   )}
              // </AutoSizer>
              <AntdRefreshList
                height={window.screen.height - 102}
                initialListSize={20}
                dataSource={radioOptions}
                refreshing={false}
                loadingMore={false}
                showFooterText={false}
                enableRefresh={false}
                noMargin
                renderRow={(item, _sectionID, index) => {
                  // projectCode
                  // 项目编号
                  // 选择项目
                  item.disabled = item.isDelete === 1 || item.disabled;
                  const isProjectId = this.props.code === 'projectId';
                  const styleTemp =
                    isProjectId
                      ? { maxWidth: '95%' }
                      : null;

                  const isProjectIdClName = isProjectId ? ' isProjectId' : '';
                  return (
                    <Radio.RadioItem
                      className={
                        item?.descTitle ? ` radio-input-list-descript ${isProjectIdClName}` : isProjectIdClName
                      }
                      key={index}
                      checked={this.state.selectedValue?.value === item?.value}
                      onClick={() => this.handleChecked(item, fieldProps)}
                      disabled={this.props.disabled || item?.disabled}
                    >
                      {!item?.descTitle ? (
                        <div style={
                          this.props.disabled || item?.disabled
                            ? disabledStyle
                            : enableStyle
                        }
                        >
                          {item?.label}
                        </div>
                      ) : (
                        <div
                          style={
                            this.props.disabled || item?.disabled
                              ? disabledStyle
                              : enableStyle
                          }
                        >
                          {item?.descValue !== -1 && (
                            <>
                              <div>
                                <span className="title-text" style={styleTemp}>
                                  {/* {item?.label} */}
                                  <>
                                    {/* {
                                      isProjectId &&
                                      <span style={{ marginRight: 5 }}>{Number(index) + 1}.</span>
                                    } */}
                                    {item?.label}
                                  </>
                                </span>
                                {item?.descValue === 0 && !isProjectId ? (
                                  <span className="tag-style">余额不足</span>
                                ) : null}
                              </div>
                              <div style={{ color: '#999', fontSize: '12px' }}>
                                {item?.descTitle +
                                  '' +
                                  (item?.descValue != undefined
                                    ? item?.descValue
                                    : '--')}
                              </div>
                              {
                                isProjectId &&
                                <div style={{ color: '#999', fontSize: '12px' }}>
                                  项目编号：{item?.projectCode || ''}
                                </div>
                              }
                            </>
                          )}

                          {item?.descValue === -1 && (
                            <>
                              <div>
                                <span className="title-text">
                                  {item?.label}
                                </span>
                              </div>
                              <div style={{ fontSize: '12px' }}>
                                {item?.descTitle + '不限额'}
                              </div>
                            </>
                          )}
                        </div>
                      )}
                    </Radio.RadioItem>
                  );
                }}
                onRefresh={this.handleRefresh}
                onEndReached={this.handleLoadMore}
              />
            ) : this.state.loading ? (
              <div className="loadingIconWrap">
                {/* <Icon type="loading" size="md" /> */}
                <i className="iconfont iconjiazai" />
              </div>
            ) : enableSearch && !searchValue ? null : (
              <div style={{ textAlign: 'center' }}>
                <img
                  src={noDataImg}
                  alt=""
                  style={{ width: '120px', height: '120px' }}
                />
                <span style={{ display: 'block', color: '#B8B8B8' }}>
                  {this.props.notFoundContent}
                </span>
              </div>
            )}
          </List.Item>
        </List>
      </Modal>
    );
  };

  // rowRenderer = ({ key, index, style }: ListRowProps, radioOptions: any[], fieldProps: any) => {
  //   const enableStyle = {
  //     color: '#222222'
  //   };
  //   const disabledStyle = {
  //     color: '#999999'
  //   };
  //   return (
  //     <Radio.RadioItem
  //       style={style}
  //       className={radioOptions[index]?.descTitle ? 'radio-input-list-descript' : ''}
  //       key={key}
  //       checked={this.state.selectedValue?.value === radioOptions[index]?.value}
  //       onClick={() => this.handleChecked(radioOptions[index], fieldProps)}
  //       disabled={this.props.disabled || radioOptions[index]?.disabled}
  //     >
  //       {
  //         !radioOptions[index]?.descTitle ?
  //           radioOptions[index]?.label
  //           : (
  //             <div style={this.props.disabled || radioOptions[index]?.disabled ? disabledStyle : enableStyle}>
  //               <div>
  //                 <span className="title-text">{radioOptions[index]?.label}</span>
  //                 {
  //                   radioOptions[index]?.descValue === 0 ? <span className="tag-style">余额不足</span> : null
  //                 }
  //               </div>
  //               <div style={{ color: '#999', fontSize: '12px' }}>
  //                 {radioOptions[index]?.descTitle + '' + (radioOptions[index]?.descValue != undefined ? radioOptions[index]?.descValue : '--')}
  //               </div>
  //             </div>
  //           )
  //       }
  //     </Radio.RadioItem>
  //   );
  // }

  public render() {
    const { getFieldProps } = this.props.form || {};
    const {
      error,
      form,
      name,
      code,
      required,
      placeholder,
      options,
      ...otherProps
    } = this.props;

    let whichOptions = this.props.useExternal ? this.state.options : options;
    const { customOptionItem, isSetCustomItem } = this.state;

    if (customOptionItem?.value) {
      // 限制用户仅能输入一个自定义选项 (因为是单选)
      if (isSetCustomItem) {
        whichOptions[0] = customOptionItem;
        // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
        // @ts-ignore
        whichOptions = [...whichOptions];
      } else {
        whichOptions = [customOptionItem, ...whichOptions];
      }
    }
    whichOptions.forEach((item: any) => {
      item.label = item.text;
      // if (item.disabled === false && this.props.externalOption?.formatVal?.valueType !== 'string') {
      //   item.disabled = item.descValue === 0 ? true : false;
      // }
    });
    let fieldProps: any = {};

    if (getFieldProps) {
      const rules = this.props.rules || [];
      fieldProps = {
        ...getFieldProps(this.props.code, {
          rules: [
            { required: this.props.required, message: `请选择${name}` },
            ...rules
          ]
        })
      };
    }

    const extra = form?.getFieldValue(code)?.text || (
      // this.props.formValues?.[code]?.text ||
      <span style={{ color: '#B8B8B8' }}>{placeholder}</span>
    );

    return (
      <div className={styles.radioSelectContainer}>
        <List.Item
          arrow="horizontal"
          onClick={this.showModal}
          extra={extra}
          {...otherProps}
          {...fieldProps}
          className={
            'radio-select-wrap ' + this.props.disabled ? 'disabled' : ''
          }
        >
          {name}
        </List.Item>
        {this.modal(whichOptions, fieldProps)}
      </div>
    );
  }
}
